import { createRouter, createWebHashHistory } from "vue-router";
import routes, { Meta } from "./routes";

const router = createRouter({
    history: createWebHashHistory(),
    routes,
    // 激活时的滚动行为
    scrollBehavior(to, _from, savedPosition) {
        const meta = to.meta as Meta;
        if (meta.scroll.length) {
            meta.scroll.forEach((v) => {
                if (v.el instanceof HTMLElement) {
                    v.el.scrollTop = v.top;
                    v.el.scrollLeft = v.left;
                } else if (v.el) {
                    let oEl = document.querySelector(v.el);
                    oEl && ((oEl.scrollTop = v.top), (oEl.scrollLeft = v.left));
                }
            });
        }
        return savedPosition ? savedPosition : { top: 0 };
    },
});
// 配置跳转前要做什么
router.beforeEach((to, from, next) => {
    const toMeta = to.meta as Meta;
    const fromMeta = from.meta as Meta;
    roleCheck();
    scrollCheck();
    // 身份判断
    function roleCheck() {
        if (toMeta.needLogin) {
            if (localStorage.getItem("token") && localStorage.getItem("role")) {
                if (toMeta.access.length > 0) {
                    if (toMeta.access.includes(localStorage.getItem("role") || "")) {
                        next();
                    } else {
                        alert("您没有权限。");
                        setTimeout(() => next("/login"), 1000);
                    }
                } else {
                    next();
                }
            } else {
                alert("您需要登录。");
                setTimeout(() => next("/login"), 1000);
            }
        } else {
            next();
        }
    }
    // 检查页面滚动距离
    function scrollCheck() {
        if (fromMeta.scroll.length) {
            fromMeta.scroll.forEach((v) => {
                if (v.el instanceof HTMLElement) {
                    v.top = v.el.scrollTop;
                    v.left = v.el.scrollLeft;
                } else if (v.el) {
                    let oEl = document.querySelector(v.el);
                    oEl && ((v.top = oEl.scrollTop), (v.left = oEl.scrollLeft));
                }
            });
        }
    }
});
// 配置跳转后要做什么
router.afterEach((to, _from) => {
    const toMeta = to.meta as Meta;
    pageInit();
    // 页面初始化
    function pageInit() {
        document.title = toMeta.title;
    }
});

export default router;
